package cn.itcast.nems.studentrecord.web.controller.b;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.bean.Page;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.PageQueryModel;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.common.util.NumberUtil;
import cn.itcast.nems.journal.dto.JournalRefundModel;
import cn.itcast.nems.studentrecord.dto.refund.JournalRefundRollbackDTO;
import cn.itcast.nems.journal.service.JournalRefundService;
import cn.itcast.nems.journal.util.JournalRefundUtil;
import cn.itcast.nems.manager.util.CustomBeanUtil;
import cn.itcast.nems.manager.util.RequestToEntityConverter;
import cn.itcast.nems.studentrecord.dao.condition.ApprovalType;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalRefundDO;
import cn.itcast.nems.studentrecord.dto.refund.JournalRefundDTO;
import cn.itcast.nems.studentrecord.web.vo.form.JournalRefundEditVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 退费凭单-头 前端控制器
 * </p>
 *
 * @author 刘曙
 * @since 2024-02-29
 */
@RestController
@RequestMapping("/b/journal/refund")
@RequiredArgsConstructor
@Slf4j
public class JournalRefundController {
    private final JournalRefundService journalRefundService;

    /**
     * <p>
     * 重读凭单分页查询
     * </p>
     *
     * @param approvalType 审批类型
     * @param pageNumber   页码
     * @param pageSize     每页显示最大条目
     * @return 分页数据
     * @author zhouwei
     * @since 2023/12/14 11:48 AM
     **/
    @GetMapping(value = {"/list/{approval_type}"})
    public ResponseEntity<Page<JournalRefundDTO>> list(HttpServletRequest request,
                                                       @PathVariable("approval_type") String approvalType,
                                                       @RequestParam(value = "page_number", required = false) Integer pageNumber,
                                                       @RequestParam(value = "page_size", required = false) Integer pageSize) {
        Assert.notNull(approvalType, BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY, "审批类型"));
        JournalRefundModel queryVO = (JournalRefundModel) RequestToEntityConverter.convert(request, JournalRefundModel.class);
        queryVO.setApprovalType(ApprovalType.valueOf(approvalType.toUpperCase()));
        PageQueryModel<JournalRefundModel> queryModel = new PageQueryModel<>(pageNumber, pageSize, queryVO);
        queryModel.convert();
        IPage<JournalRefundDO> pageData = journalRefundService.findPageList(queryModel);
        List<JournalRefundDTO> list = Objects.isNull(pageData) || CollectionUtil.isEmpty(pageData.getRecords()) ?
                null :
                pageData.getRecords().stream().map(this::transferToJournalRefundDTO).toList();
        return ResponseEntity.ok().body(
                Page.of(
                        queryModel.getPageNumber(),
                        queryModel.getPageSize(),
                        Objects.nonNull(pageData) ? Long.valueOf(pageData.getTotal()).intValue() : 0,
                        list
                )
        );
    }

    private JournalRefundDTO transferToJournalRefundDTO(JournalRefundDO journalRefundDO) {
        JournalRefundDTO journalRefundDTO = CustomBeanUtil.copyProperties(journalRefundDO, new JournalRefundDTO());
        journalRefundDTO.setAmount(NumberUtil.convertToYuan(journalRefundDO.getAmount()));
        return journalRefundDTO;
    }

    /**
     * <p>
     * 校验支付单号唯一性
     * </p>
     *
     * @param no  退费支付单号
     * @author zhouwei
     * @since 2024/4/10 10:30 AM
     **/
    @GetMapping(value = "/payment_no/{no}")
    public ResponseEntity<Boolean> checkPaymentUnique(@PathVariable(value = "no",required = false) String no) {
        log.info("【退费凭单查询详情】请求参数 no：{}", no);
        Assert.notEmpty(no , BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY, "退费支付单号")) ;
        return ResponseEntity.ok().body(journalRefundService.checkPaymentNoUnique(no));
    }

    /**
     * <p>
     * 查询退费凭单详情
     * </p>
     *
     * @param id 凭单ID
     * @author zhouwei
     * @since 2024/3/21 5:28 PM
     **/
    @GetMapping(value = "/{id}")
    public ResponseEntity<JournalRefundDTO> getById(@PathVariable("id") String id) {
        log.info("【退费凭单查询详情】请求参数 ID：{}", id);
        JournalRefundDTO refundDTO = journalRefundService.findById(id);
        return ResponseEntity.ok().body(refundDTO);
    }

    /**
     * <p>
     * 新建/提交退费凭单
     * </p>
     *
     * @param refundEditVO 表单数据
     * @return id  凭单ID
     * @author zhouwei
     * @since 2024/3/21 5:28 PM
     **/
    @PostMapping
    public ResponseEntity<String> create(@RequestBody @Validated JournalRefundEditVO refundEditVO) {
        JournalRefundDTO refundDTO = CustomBeanUtil.copyProperties(refundEditVO, new JournalRefundDTO());
        return ResponseEntity.ok().body(journalRefundService.create(refundDTO));
    }

    /**
     * <p>
     * 新建退学退回
     * </p>
     *
     * @param refundRollbackDTO 表单数据
     * @return id  凭单ID
     * @author zhouwei
     * @since 2024/3/21 5:28 PM
     **/
    @PostMapping("/rollback")
    public ResponseEntity<Boolean> createRollback(@RequestBody JournalRefundRollbackDTO refundRollbackDTO) {
        JournalRefundUtil.validateJournalRollbackDTO(refundRollbackDTO);
        return ResponseEntity.ok().body(journalRefundService.addRollback(refundRollbackDTO));
    }

    /**
     * <p>
     * 保存操作/提交退费凭单
     * </p>
     *
     * @param refundEditVO 表单数据
     * @author zhouwei
     * @since 2024/3/21 5:28 PM
     **/
    @PutMapping
    public ResponseEntity<Boolean> update(@RequestBody @Validated JournalRefundEditVO refundEditVO) {
        Assert.notNull(Objects.nonNull(refundEditVO) && Objects.nonNull(refundEditVO.getId()), BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY, "ID"));
        JournalRefundDTO refundDTO = CustomBeanUtil.copyProperties(refundEditVO, new JournalRefundDTO());
        return ResponseEntity.ok().body(journalRefundService.update(refundDTO));
    }

    /**
     * <p>
     * 删除凭单
     * </p>
     *
     * @param id 凭单ID
     * @author zhouwei
     * @since 2024/3/21 5:29 PM
     **/
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<Boolean> delete(@PathVariable("id") String id) {
        return ResponseEntity.ok().body(journalRefundService.delete(id));
    }

    /**
     * 退费凭单-分页列表-提交凭单
     *
     * @param id 升级凭单ID
     * @return 是否成功
     **/
    @PutMapping("/flow/{id}")
    public ResponseEntity<Boolean> flow(@PathVariable("id") String id) {
        return ResponseEntity.ok(journalRefundService.flow(id));
    }

}
